#include <my_header2.h>

int main(int argc, char *argv[])
{
    char* ip = "192.168.244.135";
    char* port = "8080";

    
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr* )&addr, sizeof(addr));

    // 先接收文件名长度
    int filename_len;
    int ret = recv(socket_fd, &filename_len, sizeof(int), 0);
    ERROR_CHECK(ret, -1, "recv1");
    // 再接收文件名
    char filename[60] = {0};
    ret = recv(socket_fd, filename, filename_len, 0);
    ERROR_CHECK(ret, -1, "recv2");
    
    // 依照接收到的文件名创建一个文件
    int file_fd = open(filename, O_RDWR|O_CREAT, 0666);
    ERROR_CHECK(file_fd, -1, "open");


    // 接收文件总长度
    off_t file_len;
    ret = recv(socket_fd, &file_len, sizeof(off_t), 0);
    ERROR_CHECK(ret, -1, "recv3");
    
    // 一定不要忘了要先划出地接
    ftruncate(file_fd, file_len);

    // 创建内存映射区
    char* p = (char*)mmap(NULL, file_len, PROT_WRITE|PROT_READ, MAP_SHARED, file_fd, 0);
    ERROR_CHECK(p, NULL, "mmap");

    // 接收文件到内存映射区
    ret = recv(socket_fd, p, file_len, MSG_WAITALL);
    ERROR_CHECK(ret, -1, "recv4");

    munmap(p, file_len);
    close(file_fd);
    close(socket_fd);
    return 0;
}

